//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2006
//
// Dialog for editing key-value pair.
//

# include "StdAfx.h"
# include "Resource.h"
# include "EditKVPair.h"
# include "Globals.h"

struct edit_kvp_t {
	string_t * pKey;
	string_t * pValue;
	const char * strTitle;
};

static
INT_PTR CALLBACK _EditProc (HWND _hWnd, UINT _uMsg, WPARAM _wParam, LPARAM _lParam) {
	switch (_uMsg) {
		case WM_INITDIALOG: {
			edit_kvp_t * const pData = reinterpret_cast<edit_kvp_t *> (_lParam);
			::SetWindowLong (_hWnd, GWL_USERDATA, _lParam);

			// Title.
			::SetWindowText (_hWnd, pData->strTitle);

			// Key.
			const HWND hKey = ::GetDlgItem (_hWnd, IDC_KEY);
			assert (pData->pKey != NULL);
			::SetWindowText (hKey, pData->pKey->c_str ());

			// Value.
			const HWND hValue = ::GetDlgItem (_hWnd, IDC_VALUE);
			assert (pData->pValue != NULL);
			::SetWindowText (hValue, pData->pValue->c_str ());

			// OK.
			::EnableWindow (::GetDlgItem (_hWnd, IDOK), FALSE);

			return TRUE;
		}

		case WM_COMMAND: {
			switch (LOWORD (_wParam)) {
				case IDC_KEY:
				case IDC_VALUE: {
					if (HIWORD (_wParam) == EN_CHANGE) {
						const HWND hKey = ::GetDlgItem (_hWnd, IDC_KEY);
						const size_t cKeyLen = ::GetWindowTextLength (hKey);
						::EnableWindow (::GetDlgItem (_hWnd, IDOK), cKeyLen != 0);
					}
					return TRUE;
				}

				case IDOK: {
					edit_kvp_t * const pData = reinterpret_cast<edit_kvp_t *> (::GetWindowLong (_hWnd, GWL_USERDATA));

					// Key.
					{
						const HWND hText = ::GetDlgItem (_hWnd, IDC_KEY);
						const size_t cLen = ::GetWindowTextLength (hText);
						char * const strText = reinterpret_cast<char *> (alloca (cLen + 1));
						::GetWindowText (hText, strText, cLen + 1);

						assert (pData->pKey != NULL);
						pData->pKey->assign (strText);
					}

					// Value.
					{
						const HWND hText = ::GetDlgItem (_hWnd, IDC_VALUE);
						const size_t cLen = ::GetWindowTextLength (hText);
						char * const strText = reinterpret_cast<char *> (alloca (cLen + 1));
						::GetWindowText (hText, strText, cLen + 1);

						assert (pData->pValue != NULL);
						pData->pValue->assign (strText);
					}

					::EndDialog (_hWnd, 0);

					return TRUE;
				}

				case IDCANCEL:
					::EndDialog (_hWnd, 1);
					return TRUE;
			}
		}
	}

	return FALSE;
}

bool EditKVPair (HWND _hWnd, string_t & _strKey, string_t & _strValue, const char * _strTitle) {
	edit_kvp_t data = {& _strKey, & _strValue, _strTitle};
	return DlgBox (IDD_EDIT_KVPAIR,	_hWnd, _EditProc, reinterpret_cast<LPARAM> (& data)) == 0;
}
